/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package hbPackage;

import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import hbPackage.DatabaseAccess;
import hbPackage.itemClass;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import javax.servlet.http.HttpSession;

/**
 *
 * @author windySwing
 */
public class orderRecordSvl extends HttpServlet {

    /** 
     * Processes requests for both HTTP <code>GET</code> and <code>POST</code> methods.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    protected void processRequest(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        response.setContentType("text/html;charset=UTF-8");
        PrintWriter out = response.getWriter();

        HttpSession session = request.getSession();

        try {
            DatabaseAccess da = new DatabaseAccess();

            SimpleDateFormat sf = new SimpleDateFormat("MM/dd/yyyy");

            int _itemID = Integer.parseInt(request.getParameter("dpd_itemName"));
            int _quantity = Integer.parseInt(request.getParameter("txt_quantity"));
            int _storeID = Integer.parseInt(request.getParameter("hid_storeID"));
            int _orderID = 0;

            //calculate discount
            int _discountPercent = da.getItemDiscount(_itemID, _storeID, "available");            

            //get itemDetail
            itemClass _item = da.getItem(_itemID);

            // canculate item final price
            double _totalPrice = (_item.getPrice() * _quantity);
            double _finalPrice = _totalPrice - ((_totalPrice * _discountPercent) / 100);

            //update wareHouse, minus value at quantity column
            wareHouseClass _wareHouse = da.getWareHouse(_storeID, _itemID);
            int tempQuantity = _wareHouse.getQuantity();
            int newQuantiy = tempQuantity - _quantity;
            String[] _key = {"Quantity"};
            ArrayList arrWareHouse = new ArrayList();
            arrWareHouse.add(newQuantiy);
            String[] _condition = {("store_ID=" + Integer.toString(_storeID)), ("item_ID=" + Integer.toString(_itemID))};            

            da.Update("WareHouse", _key, arrWareHouse, _condition);

            //check the order is repeated
            Object _orderIDObject = session.getAttribute("orderID");
            if (_orderIDObject != null) { //update totalPayment
                _orderID = Integer.parseInt(_orderIDObject.toString());

                orderClass _order = da.getOrder(_orderID);
                double oldTotalPayment = _order.getTotalPayment();
                double newTotalPayment = oldTotalPayment + _finalPrice;

                String[] _keyOrder = {"totalPayment"};
                ArrayList arrOrder = new ArrayList();
                arrOrder.add(newTotalPayment);
                String[] _orderCondition = {("orderID=" + Integer.toString(_orderID))};

                da.Update("[Order]", _keyOrder, arrOrder, _orderCondition);

            } else { //this order is new
                //add new order, status pending
                double _totalPayment = _finalPrice;
                String _status = "Pending";
                Date today = new Date();
                String strToday = sf.format(today);

                ArrayList arrOrder = new ArrayList();
                arrOrder.add(_storeID);
                arrOrder.add(_totalPayment);
                arrOrder.add(_status);
                arrOrder.add(strToday);

                da.Insert("[Order]", arrOrder);

                //get Last Order
                _orderID = da.getLastOrderID();
                //add to session
                session.setAttribute("orderID", _orderID);
            }

            //add one orderDetail entity            

            ArrayList orderDetailArr = new ArrayList();
            orderDetailArr.add(_orderID);
            orderDetailArr.add(_itemID);
            orderDetailArr.add(_item.getItemName());            
            orderDetailArr.add(_quantity);
            orderDetailArr.add(_item.getPrice());
            orderDetailArr.add(_discountPercent);
            orderDetailArr.add(_totalPrice);
            orderDetailArr.add(_finalPrice);

            da.Insert("OrderDetail", orderDetailArr);

            //get all orderdetail
            ArrayList allOrderDetail = da.getListOrderDetail(_orderID);
            // add session
            session.setAttribute("orderDetailList", allOrderDetail);
            

            //forward
            out.println("<script>window.location=\"admin/recordOrder.jsp\";</script>");


        } finally {
            out.close();
        }
    }

    // <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
    /** 
     * Handles the HTTP <code>GET</code> method.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }

    /** 
     * Handles the HTTP <code>POST</code> method.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }

    /** 
     * Returns a short description of the servlet.
     * @return a String containing servlet description
     */
    @Override
    public String getServletInfo() {
        return "Short description";
    }// </editor-fold>
}
